package org.quickjsf.core.annotations;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

public class MRelationHandler {
	
	public static void handlerRelation(Class<? extends Object>[] domainClasses, Map<String, List<MappingRelation>> relationMap) {
		for (Class<? extends Object> cls : domainClasses) {
			Method[] declaredFields = cls.getDeclaredMethods();
			for (Method method : declaredFields) {
				MRelation annotationRelation = method.getAnnotation(MRelation.class);
				if (method.getName().startsWith("get") && null != annotationRelation) {
					if (relationMap.get(cls.getSimpleName()) == null) {
						relationMap.put(cls.getSimpleName(), new ArrayList<MappingRelation>());
					}
					String source = StringUtils.uncapitalize(method.getName().substring(3));
					Class<?> targetEntity = annotationRelation.targetEntity();
					if (targetEntity.equals(Void.class)) {
						if (method.getReturnType().isAssignableFrom(List.class) 
								|| method.getReturnType().isAssignableFrom(Set.class)) {
							targetEntity = (Class<?>) ((ParameterizedType) 
									method.getGenericReturnType()).getActualTypeArguments()[0];
							
						} else {
							targetEntity = method.getReturnType();
						}
					}
					relationMap.get(cls.getSimpleName()).add(new MappingRelation(source,
							annotationRelation.relation(), annotationRelation.mappedBy(), targetEntity));
				}
			}
		}
	}
}

